package com.bbx.taxi.client.Activity.Address;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Adapter.AddressAdapter;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.AddressMsg;
import com.bbx.taxi.client.DB.AddressDB;
import com.bbx.taxi.client.DB.Util.DBcolumns;
import com.example.mylistview.swipemenu.MyListView;
import com.example.mylistview.swipemenu.MyListView.OnMenuItemClickListener;
import com.example.mylistview.swipemenu.MyListView.OnSwipeListener;
import com.example.mylistview.swipemenu.SwipeMenu;
import com.example.mylistview.swipemenu.SwipeMenuCreator;
import com.example.mylistview.swipemenu.SwipeMenuItem;

public class AddressActivity extends BaseBBXActivity implements
		OnItemClickListener {
	@InjectView(R.id.MyListView)
	MyListView mMyListView;
	@InjectView(R.id.layout_nodata)
	LinearLayout layout_nodata;
	private AddressAdapter mAddressAdapter;
	List<Map<String, String>> list;
	private Handler handler;
	private AddressDB db_address;// 地址数据库
	private String address_id;
	public final int COLLECTFULL=0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.address);
		super.onCreate(savedInstanceState);
		setTitle(true, "常用地址", -1, "新增");
	}

	/**
	 * 读取所有数据
	 */
	public void readAllDB() {
		list.clear();
		list.addAll(db_address.readAllDB(this,Value.ADDRESS_TYPE_COLLECTE,""));
		notifyDataSetChanged(mAddressAdapter);
	}

	/**
	 * 刷新最新数据
	 */
	public void readADB() {
		list.add(0, db_address.readADB());
		notifyDataSetChanged(mAddressAdapter);
		db_address.onColse();
	}

	public void onWriteDB(String name,String city,String address, String longitude,
			String latitude) {
		if (db_address.isCollectCountFull(this)) {
			mHandler.sendEmptyMessage(COLLECTFULL);
		} else {
			db_address.onWrite(name,city, address,Double.parseDouble(longitude) , Double.parseDouble(latitude),
					Value.ADDRESS_TYPE_COLLECTE);
			readAllDB();
		}

	}

	public void onUpdate(String name,String city, String address, String longitude,
			String latitude) {
		db_address.onUpdate(address_id, name, city,address, longitude, latitude,
				Value.ADDRESS_TYPE_COLLECTE);
		readAllDB();
	}

	public void clearDB(String rowId) {
		db_address.onDelete(rowId);
	}

	/**
	 * 初始化ListView的Item菜单
	 */
	public void initswipe() {

		// step 1. create a MenuCreator
		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {
				// create "open" item
				SwipeMenuItem openItem = new SwipeMenuItem(
						getApplicationContext());
				// set item background
				openItem.setBackgroundColor(getResources()
						.getColor(R.color.red));
				// set item width
				openItem.setWidth(dp2px(65));
				// set item title
				openItem.setTitle("删除");
				// set item title fontsize
				openItem.setTitleSize(18);
				// set item title font color
				openItem.setTitleColor(Color.WHITE);
				// add to menu
				menu.addMenuItem(openItem);

				// // create "delete" item
				// SwipeMenuItem deleteItem = new SwipeMenuItem(
				// getApplicationContext());
				// // set item background
				// deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
				// 0x3F, 0x25)));
				// // set item width
				// deleteItem.setWidth(dp2px(90));
				// // set a icon
				// deleteItem.setIcon(R.drawable.ic_delete);
				// // add to menu
				// menu.addMenuItem(deleteItem);
			}
		};
		// set creator
		mMyListView.setMenuCreator(creator);

		// step 2. listener item click event
		mMyListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(int position, SwipeMenu menu, int index) {
				// ApplicationInfo item = mAppList.get(position);
				switch (index) {
				case 0:
					clearDB(list.get(position).get(DBcolumns.ADDRESS_ID));
					list.remove(position);
					notifyDataSetChanged(mAddressAdapter);
					Toast.makeText(AddressActivity.this, "删除成功",
							Toast.LENGTH_SHORT).show();
					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							mMyListView.closeMenu();
						}
					}, 200);
					break;

				}
			}
		});

		// set SwipeListener
		mMyListView.setOnSwipeListener(new OnSwipeListener() {

			@Override
			public void onSwipeStart(int position) {
				// swipe start
			}

			@Override
			public void onSwipeEnd(int position) {
				// swipe end
			}
		});
	}

	private int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_right:// 新增
			// initDataBase();
			startActivityForResult(new Intent(AddressActivity.this,
					EditAddressActivity.class).putExtra(
					AddressMsg.extra_editaddress, AddressMsg.ADDRESS_COLLECT),
					requestCode);
			break;
		default:
			super.onClick(v);
			break;
		}
	}

	@Override
	protected void initView() {
		handler = new Handler();
		db_address = new AddressDB(this);
		list = new ArrayList<Map<String, String>>();
		mAddressAdapter = new AddressAdapter(this, list);
		mMyListView.setAdapter(mAddressAdapter);
		mMyListView.setOnItemClickListener(this);
	}

	@Override
	protected void initData() {
		readAllDB();
		initswipe();
	}

	@Override
	protected void desotryItems() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == this.requestCode && resultCode == this.resultCode) {
			if (data != null) {// 新增
				String name = data.getStringExtra(AddressMsg.extra_address_name);
				String city = data.getStringExtra(AddressMsg.extra_address_city);
				String address = data.getStringExtra(AddressMsg.extra_address_address);
				String longitude =String.valueOf(data.getDoubleExtra(AddressMsg.extra_address_longitude,0));
				String latitude =String.valueOf( data.getDoubleExtra(AddressMsg.extra_address_latitude,0));
				onWriteDB(name, city,address, longitude, latitude);
			}
		}
		// 修改
		else if (requestCode == this.requestCode2
				&& resultCode == this.resultCode) {
			if (data != null) {
				String name = data.getStringExtra(AddressMsg.extra_address_name);
				String city = data.getStringExtra(AddressMsg.extra_address_city);
				String address = data.getStringExtra(AddressMsg.extra_address_address);
				String longitude =String.valueOf(data.getDoubleExtra(AddressMsg.extra_address_longitude,0));
				String latitude =String.valueOf( data.getDoubleExtra(AddressMsg.extra_address_latitude,0));
				onUpdate(name, city,address, longitude, latitude);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void notifyDataSetChanged(BaseAdapter adapter) {
		adapter.notifyDataSetChanged();
		onisShowNodata(adapter);
	}

	public void onisShowNodata(BaseAdapter adapter) {
		if (adapter.getCount() == 0) {
			layout_nodata.setVisibility(View.VISIBLE);
		} else {
			layout_nodata.setVisibility(View.GONE);
		}
	}

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
             switch(msg.what){
             case COLLECTFULL:
            	 Toast.makeText(context, "最多保存" + db_address.count_collect + "个常用地址",
     					Toast.LENGTH_SHORT).show();
            	 break;
             }
		}
	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		address_id = list.get(position).get(DBcolumns.ADDRESS_ID);
		startActivityForResult(new Intent(AddressActivity.this,
				EditAddressActivity.class).putExtra(
				AddressMsg.extra_editaddress, AddressMsg.ADDRESS_COLLECT),
				requestCode2);
	}
}
